package com.hry.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hry.store.common.Const;
import com.hry.store.dao.OrderMapper;
import com.hry.store.pojo.Order;
import com.hry.store.redis.RedisComponent;
import com.hry.store.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisComponent redis;
    /**
     * 添加订单到订单表
     * @param order
     */
    @Override
    public void addToOrder(Order order) {
        orderMapper.insert(order);
    }

    /**
     * 去订单表查询订单
     * @param userEmail
     * @param orderNo
     * @return
     */
    @Override
    public List<Order> getByEmailAndOrderNo(String userEmail, Long orderNo) {
        return orderMapper.getOrders(userEmail, orderNo);
    }

    /**
     * 根据用户邮箱去查询用户订单
     */
    public PageInfo<Order> getByEmail(String userEmail, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList = orderMapper.getByUserEmail(userEmail);
        PageInfo pageInfo = new PageInfo(orderList);
        return pageInfo;
    }

    /**
     * 查询订单状态
     * @param userEmail
     * @param orderNo
     * @return
     */
    @Override
    public List<Order> findByUserEmailAndStatus(String userEmail, Long orderNo) {
        return orderMapper.getOrder(userEmail, orderNo);
    }

    /**
     * 从redis中获取热门商品
     * @return
     */
    @Override
    public List<Order> getStartProduct() {
        // 排名前四的数据
        Set<Order> orderSet = redis.getStartProduct(Const.STRAT_PRODUCT, 0L, 4L);
        Iterator iterator = orderSet.iterator();
        List list = new ArrayList();
        while (iterator.hasNext()) {
            String json = (String) iterator.next();
            Order order = JSON.parseObject(json, Order.class);
            list.add(order);
        }
        return list;
    }
}
